package org.agiletestplus.client.ui;

import java.util.List;

import org.agiletestplus.client.objects.Project;
import org.damour.base.client.objects.PermissibleObject;
import org.damour.base.client.objects.User;
import org.damour.base.client.service.BaseServiceCache;
import org.damour.base.client.ui.IGenericCallback;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class HomePanel extends VerticalPanel {
  IGenericCallback<Project> callback = null;

  public HomePanel(IGenericCallback<Project> callback) {
    this.callback = callback;
    add(new Label("Projects"));
    // list projects
    loadObjects(null);
  }

  public void loadObjects(final User user) {
    final AsyncCallback<List<PermissibleObject>> loadCallback = new AsyncCallback<List<PermissibleObject>>() {
      public void onFailure(Throwable caught) {
      }

      public void onSuccess(final List<PermissibleObject> projects) {
        @SuppressWarnings({ "rawtypes", "unchecked" })
        List<Project> projList = (List<Project>) (List) projects;
        for (final Project obj : projList) {
          // adding objects to the list
          Anchor name = new Anchor(obj.getName());
          name.setTitle(obj.getDescription());
          name.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
              // display project panel
              callback.invoke(obj);
            }
          });

          add(name);
        }
      };
    };
    BaseServiceCache.getService().getPermissibleObjects(null, "org.agiletestplus.client.objects.Project", loadCallback);

  }

}